package DAO;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import Beans.WxUser;
import Utils.HibernateUtil;

public class WxUserDao {
	private SessionFactory sessionFactory;

	public WxUserDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}

	Transaction tr = null;
	
	/**
	 * 删除微信用户
	 */
	public void delete(WxUser wxUser) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(wxUser);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改微信用户
	 */
	public void edit(WxUser wxUser) {

		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(wxUser);
		tr.commit();
		session.close();
	}
	
	/**
	 * 保存新增的微信用户
	 */
	public void save(WxUser wxUser) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.save(wxUser);
		tr.commit();
		session.close();
	}
	
	/**
	 * 返回所有微信用户信息
	 */
	public List<WxUser> getAllwxUser(){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(WxUser.class);
		List<WxUser> wxUsers=c.list();
		tr.commit();
		session.close();
		return wxUsers;
	}
	
	/**
	 * 根据微信标识返回信息
	 */
	public List<WxUser> getWxUserByNumber(String number){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(WxUser.class);
		c.add(Restrictions.eq("number", number));
		List<WxUser> wxUsers=c.list();
		tr.commit();
		session.close();
		return wxUsers;
	}
	
	/**
	 * 根据手机号码返回信息
	 */
	public List<WxUser> getWxUserByPhone(String phone){
		Session session=sessionFactory.openSession();
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(WxUser.class);
		c.add(Restrictions.eq("phone", phone));
		c.add(Restrictions.eq("binding", 1));
		List<WxUser> wxUsers=c.list();
		tr.commit();
		session.close();
		return wxUsers;
	}

	/**
	 * 通过微信用户ID返回指定微信用户
	 * 
	 * @return
	 */
	public WxUser getWxUserById(int wxUserId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		WxUser wxUser = (WxUser) session.get(WxUser.class, wxUserId);
		tr.commit();
		session.close();
		return wxUser;
	}
}
